var site_url=localStorage.getItem("site_url");

$(function(){
	
	// localStorage.setItem("isInsurance",0)
	getProject();
	$(":checkbox[name='dataId']").click(function () {
	    $("#allCheck").prop('checked',
	        $(":checkbox[name='dataId']").length == $(":checkbox[name='dataId']:checked").length);
	});  
	//当前页数
	var pageNo=$('#pageNo').val();
	//总页数
	var total_page=$('#total_page').val();
	var keyword=$('#keyword').val();
	// getData();
	//分页
/* 	$("#page").paging({
	    pageNo: parseInt(pageNo),
	    totalPage: parseInt(total_page),
	    callback: function(num) {
	    }
	}) */
	//左侧数据
	getDataDepartment();
	//右侧员工数据
	// getUserById(1);
	//左侧数据树状显示
	$('#files').tree({
		expanded: 'li:first'
	});
	
});

var requestStatus=false;
/* 分页 x是命名，y是div分页的id，z是总条数，d是调取函数的名字 */
function publicPage(x, y, z,d) {  
    var x = new Paging();
    x.init({
        target: y,
        pagesize: 50,  //每页的条数
        count: z,
        current: 1,
        //toolbar: true,                       
        callback: function (pagecount, size) {
            if (pagecount > 1) {
                d(pagecount, size);
            }
        }
    })                
}
//查询部门
function getDeptList(type){
	
	var URL = site_url+"/depts/all";
	var userToken=localStorage.getItem("userToken");
	$.ajax({
		type:"get",
		url:URL,
		headers:{'token':userToken},
		success:function(data){
			$("#department_staff").html("");
			$("#department_staff_edit").html("");
			$.each(data, function(index, dept) { 
				var querynames = $('<option id="'+dept.id+'" value="'+dept.id+'">'+dept.name+'</option>');
				if(type==1 && dept.type==3){
					$("#department_staff").append($('<option id="'+dept.id+'" value="'+dept.id+'">'+dept.name+'</option>'));
				}else{
					// $("#department_staff_edit").append(querynames);
				}
				
			});
		}
	});
}
//查询保障工资
function getGuaranteeWagesList(){
	
	var URL = site_url+"/depts/all";
	var userToken=localStorage.getItem("userToken");
	$.ajax({
		type:"get",
		url:URL,
		headers:{'token':userToken},
		success:function(data){
			if(data!=null){
				/* $("#guarantee_salary_staff").html("");
				$("#guarantee_salary_staff_edit").html(""); */
			}
			$.each(data, function(index, dept) {
				// alert(dept.id);
				var querynames = $('<option value="'+dept.id+'">'+dept.name+'</option>');
				/* $("#guarantee_salary_staff").append(querynames);
				$("#guarantee_salary_staff_edit").append(querynames); */
			});
		}
	});
}
/* 获取角色列表 */
function getRoleList(){
	$("#role_staff").html("");
	$("#role_staff_edit").html("");
	var URL = site_url+"/roles/all";
	var userToken=localStorage.getItem("userToken");
	$.ajax({
		type:"get",
		url:URL,
		headers:{'token':userToken},
		success:function(data){
			var querynames = '';
			for (var i=0;i<data.data.length;i++) {
				querynames+='<option value="'+data.data[i].id+'">'+data.data[i].name+'</option>';
			}
			// $("#role_staff_edit").append(querynames);
			$("#role_staff").append(querynames);
			// $("#role_staff_edit").append(querynames);
		}
	});
}
/* 全选按钮 */
function selectAll(){
	// alert("ddd");
	var isCheck=$("#allCheck").is(':checked');  //获得全选复选框是否选中
	// alert(isCheck);
	$("input[type='checkbox']").each(function() {  
	    this.checked = isCheck;       //循环赋值给每个复选框是否选中
		
	});   
	// $('input[name="dataId"]:checked').prop("checked", true);
}
//部门管理左侧数据赋值
function getDataDepartment(){
	$('#left_data').html("");
	var dept = getByParentId(-1);
	var html="";
	//alert(dept.length);
	html+='<ul id="files">';
	for (var k = 0; k < dept.length; k++) {
		var deptChildren = getByParentId(dept[k].id);
		html+='<li><a href="javascript:void(0);" onclick="leftDepartClick('+dept[k].id+');"><img src="img/file_icon.png"/>&nbsp;<label id="subjectName'+dept[k].id+'">'+dept[k].name+'</label><img class="depart_add" src="img/department_add.png" onclick="popupShow(1,1,\''+dept[k].id+'\');"/></a>';								
		html+='<ul id="subject">';
		for (var i = 0; i < deptChildren.length; i++) {
			var deptChildrens = getByParentId(deptChildren[i].id);
			html+='<li id="sub'+deptChildren[i].id+'"><a href="#" onclick="leftDepartClick('+deptChildren[i].id+');"><img src="img/file_icon.png"/>&nbsp;';
			html+='<label class="depart-left-txt" id="subject'+deptChildren[i].id+'" title="'+deptChildren[i].name+'">'+deptChildren[i].name+'</label>';
			html+='<div id="operation0_'+deptChildren[i].id+'" style="display: block;float: right;" >';
			html+='<img class="depart_add" src="img/department_add.png" onclick="popupShow(2,'+dept[k].id+',\''+deptChildren[i].id+'\');"/>';
			html+='<img class="depart_add" src="img/department_edit.png" onclick="popupShow(4,'+dept[k].id+',\''+deptChildren[i].id+'\');"/>';
			html+='<img class="depart_add" src="img/department_delete.png" onclick="dataDelete(1,'+dept[k].id+',\''+deptChildren[i].id+'\');"/>';
			html+='</div>';
			html+='</a>';
			html+='<ul id="departmentUl'+deptChildren[i].id+'">';
			for(var j=0;j<deptChildrens.length;j++){
				html+='<li id="depart'+deptChildrens[j].parentId+'" onclick="popupShow(7,'+deptChildrens[j].parentId+',\''+deptChildrens[j].id+'\');"><a href="#"  onclick="leftDepartClick('+deptChildrens[j].id+');">';
				html+='<label class="depart-left-txt" id="department'+deptChildrens[j].id+'" title="'+deptChildrens[j].name+'">'+deptChildrens[j].name+'</label>';
				html+='<div id="operation'+deptChildrens[j].parentId+'_'+deptChildrens[j].id+'" style="display: none;float: right;" >';
				html+='<img class="depart_add" src="img/department_add.png" onclick="popupShow(3,'+deptChildrens[j].parentId+',\''+deptChildrens[j].id+'\');"/>';
				html+='<img class="depart_add" src="img/department_edit.png" onclick="popupShow(5,'+deptChildrens[j].parentId+',\''+deptChildrens[j].id+'\');"/>';
				html+='<img class="depart_add" src="img/department_delete.png" onclick="dataDelete(2,'+deptChildrens[j].parentId+',\''+deptChildrens[j].id+'\');"/>';
				html+='</div>';
				html+='</a></li>';
			}
			html+='</ul>';
			html+='</li>';
		}
		html+='</ul>';
		html+='</li>';
	}
	html+='</ul>';
	
	
	$('#left_data').html(html);
	
	//左侧数据树状显示
	$('#files').tree({
		expanded: 'li:first'
	});
}
/* 树状点击 */
function leftDepartClick(id){
	requestStatus=false;
	$('#pageNo').val("1");
	getUserById(id);
}
/* 根据部门id获取用户数据 */
function getUserById(id){
	
	var pageNo=$('#pageNo').val();
	
	var signing=$("#is_signing option:selected").val();
	
	var start=$('#search_date_start').val();
	
	var end="";
	
	var keyword=$('#search_keyword').val();
	
	var ifSigning="";
	if(signing==1){
		ifSigning=true;
	}else{
		ifSigning=false;
	}
	
	insurance=localStorage.getItem("isInsurance");
	var valid=$("#is_valid option:selected").val();
	var URL = site_url+"/users/dept?size=10&current="+pageNo+"&signing="+signing+"&start="+start+"&end="+end+"&name="+keyword+"&insurance="+insurance+"&valid="+valid+"&deptId="+id;
	// var URL="";
	var userToken=localStorage.getItem("userToken");
	$.ajax({
		type:'GET',
		url:URL,
		headers:{'token':userToken},
		dataType:"json",
		success: function (json) {
			getDataStaff(json.data.records);
			if(json.data.records.length>0){
				var pageNo=json.data.current;
				var total_page=json.data.pages;
				localStorage.setItem("userDepartId",id);
				localStorage.setItem("total_page",total_page);
				//分页
				$("#page").paging({
				    pageNo: parseInt(pageNo),
				    totalPage: parseInt(total_page),
				    callback: function(num) {
						$('#pageNo').val(num);
						var total_page=localStorage.getItem("total_page");
						var did=localStorage.getItem("userDepartId");
						requestStatus=true;
						$("#page").paging({
						    pageNo: parseInt(num),
						    totalPage: parseInt(total_page)
						})
						getUserById(did);
						$("#page").stopPagination({});
				    }
				})
			}
	    }
	});
}

/* 弹窗页面显示 */ 
function popupShow(type,parent_id,id){
	// alert("parent_id="+parent_id);
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		switch(type){
			//添加项目部
			case 1:
				getDeptById(id,1);
				$('#subjectAdd').show();
				break;
			//添加部门
			case 2:
				getDeptById(id,2);
				$("#departmentId").val(parent_id);
				
				$('#departmentAdd').show();
				break;
			//添加人员
			case 3:
				getRoleList();
				getDeptList(1);
				// getGuaranteeWagesList();
				var baozhang = getBaoZhang();
				var job = getPositionType();
				$("#position_staff").html("");
				$("#guarantee_salary_staff").html("");
				// var political = getPolitical();
				for(var i=0;i<job.length;i++){
					$("#position_staff").append( $('<option value="'+job[i].value+'">'+job[i].label+'</option>'));
				}
				
				for(var i=0;i<baozhang.length;i++){
					$("#guarantee_salary_staff").append( $('<option value="'+baozhang[i].value+'">'+baozhang[i].label+'</option>'));
				}
				
				// for(var i=0;i<political.length;i++){
				// 	$("#political").append( $('<option value="'+political[i].value+'">'+political[i].label+'</option>'));
				// }
				
				$('#staffAdd').show();
				break;
			//项目部编辑
			case 4:
				getDeptList(2);
				$("#subjectId").val(id);
				var subject=$("#subject"+id).text();
				var subjectParent=$("#subjectName"+parent_id).text();
				
				var option = $('<option value="'+parent_id+'">'+subjectParent+'</option>');
				$("#partent_name_edit").html(option);
				$("#subject_name_edit").val(subject);
				
				$('#subjectEdit').show();
				break;
			//部门编辑
			case 5:
				$("#dataId").val(id);
				$("#departmentId").val(id);
				var depart=$("#department"+id).text();
				$("#department_name_edit").val(depart);   
				
				var subjectParent=$("#subject"+parent_id).text();
				var option = $('<option value="'+parent_id+'">'+subjectParent+'</option>');
				
				$("#partent_subject_edit").html(option);//部门
				
				$('#departmentEdit').show();
				break;
			//人员编辑
			case 6:
				var userInfo = getByUserId(id);
				console.log(userInfo)
				// getRoleList();
				// getDeptList(2);
				var depart = getDepart();
				var role = getRole();
				var baozhang = getBaoZhang();
				var job = getPositionType();
				$("#department_staff_edit").html("");
				$("#position_staff_edit").html("");
				$("#guarantee_salary_staff_edit").html("");
				$("#role_staff_edit").html("");
				for(var i=0;i<depart.length;i++){
					$("#department_staff_edit").append( $('<option value="'+depart[i].id+'">'+depart[i].name+'</option>'));
				}
				for(var i=0;i<role.length;i++){
					$("#role_staff_edit").append( $('<option value="'+role[i].id+'">'+role[i].name+'</option>'));
				}
				for(var i=0;i<job.length;i++){
					if(userInfo.job==job[i].label){
						$("#position_staff_edit").append( $('<option value="'+job[i].value+'" selected = "selected" >'+job[i].label+'</option>'));
					}else{
						$("#position_staff_edit").append( $('<option value="'+job[i].value+'">'+job[i].label+'</option>'));
					}
					
				}
				for(var i=0;i<baozhang.length;i++){
					if(userInfo.baozhang==baozhang[i].value){
						$("#guarantee_salary_staff_edit").append( $('<option value="'+baozhang[i].value+'" selected = "selected" >'+baozhang[i].label+'</option>'));
					}else{
						$("#guarantee_salary_staff_edit").append( $('<option value="'+baozhang[i].value+'">'+baozhang[i].label+'</option>'));
					}
				
				}
				
				$("#id_staff_edit").val(id);
				$("#department_staff_edit").val(userInfo.deptId==undefined?"":userInfo.deptId); //部门
				$("#username_staff_edit").val(userInfo.name==undefined?"":userInfo.name);     //姓名
				// $("#position_staff_edit").val(userInfo.job==null?"":userInfo.job);     //职位
				$("#phone_staff_edit").val(userInfo.phone==null?"":userInfo.phone);           //电话
				$("#ID_staff_edit").val(userInfo.idCardNo==null?"":userInfo.idCardNo);       //身份证
				$("#education_staff_edit").val(userInfo.education==null?"":userInfo.education);              //学历
				$("#entry_date_edit").val(userInfo.entryTime==null?"":userInfo.entryTime);          //入职时间
				$("#contract_date_edit").val(userInfo.hireTime==null?"":userInfo.hireTime);       //合同时间
				$("#position_salary_staff_edit").val(userInfo.gangwei==null?"":userInfo.gangwei);   //岗位工资
				// $("#guarantee_salary_staff_edit").val(userInfo.baozhang==null?"":userInfo.baozhang);  //保障工资
				$("#head_img_edit").attr("src",userInfo.avatar==undefined?"":userInfo.avatar);//头像
				$("#social_insurance_base_edit").val(userInfo.wxjishu==undefined?"":userInfo.wxjishu);
				//新加字段
				$("#address_edit").val(userInfo.currentResidence==undefined?"":userInfo.currentResidence);   //家庭住址
				$("#major_edit").val(userInfo.professional==undefined?"":userInfo.professional);     //专业
				$("#political_edit").val(userInfo.politicalStatus==undefined?"":userInfo.politicalStatus); //政治面貌
				$("#role_staff_edit").val(userInfo.roleId==undefined?"":userInfo.roleId); //角色
				// alert(userInfo.politicalStatus);
				if(userInfo.annualSalary){
					$("#annual_salary_edit").prop("checked", true);
				}else{
					$("#annual_salary_edit").prop("checked", false);
				}
				// $("#annual_salary_edit").val(userInfo.annualSalary);                      //是否拿年薪
				var baozhang=$("#guarantee_salary_staff_edit option:selected");
				var num=baozhang.text();
				if(num==null || num==""){
					num=0;
				}
				var sum=parseFloat(userInfo.gangwei)+parseFloat(num);
				$("#depart_desc_edit").text("岗位工资"+userInfo.gangwei+"+保障工资"+num+"，共"+sum+"元"); 
				$('#staffEdit').show();
				
				break;
			//点击一行之后显示操作按钮(部门)
			case 7:
				var lastPartentId=localStorage.getItem("department_click_partent");
				var lastId=localStorage.getItem("department_click");
				// alert(lastPartentId);
				//隐藏上次点击的数据
				$('#operation'+lastPartentId+'_'+lastId).css('display','none');
				//显示本次点击的数据
				$('#operation'+parent_id+'_'+id).css('display','block');
				/* for(var i=1;i<30;i++){
					if(i==id){
						$('#operation'+i).css('display','block');
					}else{
						$('#operation'+i).css('display','none');
					}
				} */
				localStorage.setItem("department_click_partent",parent_id);
				localStorage.setItem("department_click",id);      
				break;
			//点击一行之后显示操作按钮(项目部)
			case 8:
				var lastPartentId=localStorage.getItem("department_click_partent");
				var lastId=localStorage.getItem("department_click");
				// alert(lastPartentId);
				//隐藏上次点击部门的数据
				if(lastPartentId!=null){
					$('#operation'+lastPartentId+'_'+lastId).css('display','none');
				}
				
				var lastPartentId=localStorage.getItem("sub_click_partent");
				var lastId=localStorage.getItem("sub_click");
				//隐藏上次点击的数据
				$('#depart_oper1_'+lastId).css('display','none');
				//显示本次点击的数据
				$('#depart_oper1_'+id).css('display','block');
				
				localStorage.setItem("sub_click_partent",parent_id);
				localStorage.setItem("sub_click",id);
			
				break;
			//保障工资添加的类型弹窗显示
			case 9:
				$("#operationId").val(1);
				$("#typeDiv").show();
				break;
			//保障工资编辑的类型弹窗显示
			case 10:
				$("#operationId").val(2);
				$("#typeDiv").show();
				break;
			//部门的添加职位弹窗显示(id  1:添加  2：编辑)
			case 11:
				$("#addPositionId").val(id);
				$("#addPositionDiv").show();
				break;
		}
	});	
}
/* 输入数字的监听事件 type 1:添加  2：编辑*/
function numChange(type){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		if(type==1){
			var num1=$("#position_salary_staff").val();
			if(num1<0){
				layer.alert("数字不能小于0！", {icon: 5});
				return;
			}
			var num2=$("#guarantee_salary_staff option:selected").text();
			var sum=parseFloat(num1==(null || "")?"0":num1)+parseFloat(num2==null?"0":num2);
			$("#depart_desc").text("岗位工资"+num1+"+保障工资"+num2+"，共"+sum+"元"); 
		}else{
			var num1=$("#position_salary_staff_edit").val();
			if(num1<0){
				layer.alert("数字不能小于0！", {icon: 5});
				return;
			}
			var num2=$("#guarantee_salary_staff_edit option:selected").text();
			var sum=parseFloat(num1==(null || "")?"0":num1)+parseFloat(num2==null?"0":num2);
			$("#depart_desc_edit").text("岗位工资"+num1+"+保障工资"+num2+"，共"+sum+"元"); 
		}
		
	});	
	
}
/* 删除 */
function dataDelete(type,parent_id,id){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		var chk_value = [];
		var URL = "";
		
		var userToken = localStorage.getItem("userToken");
		
		switch(type){
			//删除项目部
			case 1:
				layer.confirm('您确定删除吗？', { icon: 3, title: '提示',shade:0 }, function (index) {
					URL = site_url+"/depts?id="+id;
					removeById(URL);
					layer.close(index);
				});
			
				break;
			//删除部门
			case 2:
				layer.confirm('您确定删除吗？', { icon: 3, title: '提示',shade:0 }, function (index) {
					URL = site_url+"/depts?id="+id;
					removeById(URL);
					// $("#departmentUl"+parent_id+" li[id=depart'"+(id-1)+"']").remove(); 
					layer.close(index);
				});
				
				break;
			//删除人员
			case 3:
				layer.confirm('您确定删除吗？', { icon: 3, title: '提示',shade:0 }, function (index) {
					URL = site_url+"/depts?id="+id;
					deleteUserById(id);
					$(this).closest('tr').remove();
					layer.close(index);
				});
				 
				break;
			//批量删除人员
			case 4:
			
			layer.confirm('您确定删除吗？', { icon: 3, title: '提示',shade:0 }, function (index) {
				$('input[name="dataId"]:checked').each(function () {
				    chk_value.push($(this).val());
					   this.checked = "checked"; 
				});
				id=chk_value;
				
				$.ajax({
					type:"DELETE",
					url:site_url+"/users/list/"+id,
					headers:{'token':userToken},
					contentType: 'application/json; charset=utf-8',
					success:function(data){
						layer.alert("删除成功！", {icon: 6});
						layer.close(index);
					}
				});
			});
				break;
			default:
				break;
		}
		
		
	});	
}
/* 添加项目部的关闭按钮 */
function subjectClose(){
	$("#subjectAdd").hide();
}
/* 编辑项目部的关闭按钮 */
function subjectEditClose(){
	$("#subjectEdit").hide();
}
/* 添加部门的关闭按钮 */
function departmentClose(){
	$("#department_name").val("");
	$("#department_charge").val("");
	$("#ifAdministration").attr('checked','false');
	$("#departmentAdd").hide();
}
/* 编辑部门的关闭按钮 */
function departmentEditClose(){
	$("#ifAdministration_edit").attr('checked',false);
	$("#departmentEdit").hide();
}
/* 添加人员的关闭按钮 */
function staffClose(){
	$("#staffAdd").hide();
}
/* 编辑人员的关闭按钮 */ 
function staffEditClose(){
	$("#staffEdit").hide();
}
/* 添加类型的关闭按钮 */ 
function typeClose(){
	//把类型值清空
	$("#typename").val("");
	$("#typeDiv").hide();
}
/* 添加职位的关闭按钮 */ 
function positionClose(){
	//把类型值清空
	$("#typename").val("");
	$("#addPositionDiv").hide();
}
/* 编辑项目部的保存按钮 */
function subjectEditSave(){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		var subject_name_edit = $("#subject_name_edit").val();
		var subjectId = $("#subjectId").val();
		if(subject_name_edit.length>8){
			layer.alert("文字不能超过8个！", {icon: 5});
			return;
		}
		
		var URL = site_url+"/depts";
		var userToken=localStorage.getItem("userToken");
		
		$.ajax({
			type:"PUT",
			url:URL,
			headers:{'token':userToken},
			contentType: 'application/json; charset=utf-8',
			data:JSON.stringify({
				id:subjectId,
				name:subject_name_edit
			}),
			success:function(data){
				layer.alert("编辑成功！", {icon: 6});
			}
		});
		
	});
}
/* 添加项目部的保存按钮 */
function subjectSave(){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		var subject_name = $("#subject_name").val();
		var partent_name_add = $("#partent_name_add").val();
		if(subject_name.length>8){
			layer.alert("文字不能超过8个！", {icon: 5});
			return;
		}
//		var num=$("#subject ul").length+1;
//		// alert(num);
//		var html='<li id="sub'+num+'"><a href="javascript:void(0);"><img src="img/file_icon.png"/>&nbsp;';
//		html+='<label id="subject'+num+'">'+subject_name+'</label>';
//		html+='<div id="operation0_'+num+'" style="display: block;float: right;" >';
//		html+='<img class="depart_add" src="img/department_add.png" onclick="popupShow(2,'+num+','+num+');"/>';
//		html+='<img class="depart_add" src="img/department_edit.png" onclick="popupShow(4,'+num+','+num+');"/>';
//		html+='<img class="depart_add" src="img/department_delete.png" onclick="dataDelete(1,'+num+','+num+');"/>';
//		html+='</div>';
//		html+='</a>';
//		html+='<ul id="departmentUl"'+num+'>';
//		html+='</ul>';
//		html+='</li>';
//		$("#subject").append(html);
		
		
		//左侧数据树状显示
		$('#files').tree({
			expanded: 'li:first'
		});
		$("#subject_name").val("");
		
		var URL = site_url+"/depts";
		
		var userToken=localStorage.getItem("userToken");
		
		$.ajax({
			type:"POST",
			url:URL,
			headers:{'token':userToken},
			contentType: 'application/json; charset=utf-8',
			data:JSON.stringify({
				type:2,
				name:subject_name,
				parentId:partent_name_add
			}),
			success:function(data){
				// layer.alert("保存成功！", {icon: 6});
				location.reload();
			}
		});
		
	});	
}
/* 添加部门的保存按钮 */
function departmentSave(){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		var type=3;
		var department_id = $("#departmentId").val();
		var department_name = $("#department_name").val();
		var partent_subject_add = $("#partent_subject_add").val();
		var department_charge = $("#department_charge").val();
		if(department_name==""){
			layer.alert("部门名称不能为空！", {icon: 5});
			return;
		}
		if(department_name.length>8){
			layer.alert("部门名称不能超过8个字！", {icon: 5});
			return;
		}
		//是否管理部门
		var isCheck=$("#ifAdministration").is(':checked');
		if(isCheck){
			type=4;
		}
		/* if(department_charge==""){
			layer.alert("部门负责人不能为空！", {icon: 5});
			return;
		} */
		
		$('#files').tree({
			expanded: 'li:first'
		});
		//添加后数据清空
		$("#department_name").val("");
		$("#department_charge").val("");
		$("#ifAdministration").attr('checked','false');
		
		var URL = site_url+"/depts";
		var userToken=localStorage.getItem("userToken");
		
		$.ajax({
			type:"POST",
			url:URL,
			headers:{'token':userToken},
			contentType: 'application/json; charset=utf-8',
			data:JSON.stringify({
				type:type,
				name:department_name,
				parentId:partent_subject_add
			}),
			success:function(data){
				// layer.alert("保存成功！", {icon: 6});
				location.reload();
			}
		});
		
		// layer.alert("添加成功！", {icon: 6});
	});	
}
/* 编辑部门的保存按钮 */
function departmentEditSave(){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		var type=3;
		var id = $("#dataId").val();
		var departmentId = $("#departmentId").val();
		var department_name = $("#department_name_edit").val();
		var partent_subject = $("#partent_subject_edit").val();
		var department_charge = $("#department_charge_edit").val();
		//是否管理部门
		var isCheck=$("#ifAdministration_edit").is(':checked');
		if(isCheck){
			type=4;
		}
		if(department_name.length>8){
			layer.alert("文字不能超过8个！", {icon: 5});
			return;
		}
		$("#department"+departmentId).text(department_name);
		// var aa=$("#department"+departmentId).text();
		var URL = site_url+"/depts";
		var userToken=localStorage.getItem("userToken");
		// alert(id);
		$.ajax({
			type:"PUT",
			url:URL,
			headers:{'token':userToken},
			contentType: 'application/json; charset=utf-8',
			data:JSON.stringify({
				id:id,
				type:type,
				name:department_name,
				parentId:partent_subject
			}),
			success:function(data){
				// layer.alert("======"+data, {icon: 6});
				location.reload();
			}
		});
	});	
}
/* 添加人员的保存按钮 */
function staffSave(){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
	    var deptOptions=$("#department_staff option:selected");  
		var username_staff = $("#username_staff").val();     //姓名
		var position_staff = $("#position_staff").val();     //职位
		var phone_staff = $("#phone_staff").val();           //电话
		var ID_staff = $("#ID_staff").val();                 //身份证
		var education_staff = $("#education_staff").val();   //学历
		var entry_date = $("#entry_date").val();             //入职时间
		var contract_date = $("#contract_date").val();       //合同时间
		var position_salary_staff = $("#position_salary_staff").val();   //岗位工资
		var guarantee_salary_staff = $("#guarantee_salary_staff").val();  //保障工资
		var roleOptions = $("#role_staff option:selected"); //角色
		var social_insurance_base = $("#social_insurance_base").val();//缴费基数
		var annualSalary = $("#annualSalary").prop("checked");//是否年薪
		
		var address = $("#address").val();    //家庭住址
		var professional =$("#major").val();  //专业
		var political=$("#political").val();  //政治面貌
		var head_img = "";//头像
		if (!roleOptions.val()) {
			layer.alert("请选择角色", {icon: 6});
			return;
		}
		if (position_staff=="") {
			layer.alert("职位不能为空", {icon: 6});
			return;
		}
		if (phone_staff=="") {
			layer.alert("电话不能为空", {icon: 6});
			return;
		}
		if (political=="") {
			layer.alert("政治面貌不能为空", {icon: 6});
			return;
		}
		if (ID_staff=="") {
			layer.alert("身份证不能为空", {icon: 6});
			return;
		}
		if (address=="") {
			layer.alert("家庭住址不能为空", {icon: 6});
			return;
		}
		/* if (education_staff=="") {
			layer.alert("学历不能为空", {icon: 6});
			return;
		}
		if (major=="") {
			layer.alert("专业不能为空", {icon: 6});
			return;
		} */
		if (entry_date=="") {
			layer.alert("入职时间不能为空", {icon: 6});
			return;
		}
		/* if (contract_date=="") {
			layer.alert("合同时间不能为空", {icon: 6});
			return;
		} */
		if (position_salary_staff=="") {
			layer.alert("岗位工资不能为空", {icon: 6});
			return;
		}
		if (guarantee_salary_staff=="") {
			layer.alert("保障工资不能为空", {icon: 6});
			return;
		}
		if (social_insurance_base=="") {
			layer.alert("缴费基数不能为空", {icon: 6});
			return;
		}
		var reader = new FileReader();
		// var file = $("#headFileAdd")[0].files[0];
		var file;
	    if (file) {
	        //将文件以Data URL形式读入页面  
	        var imgUrlBase64 = reader.readAsDataURL(file);
	        reader.onload = function (e) {
	        	head_img = reader.result
    			var data = {
    				deptId:parseInt(deptOptions.val()),
    				deptName:deptOptions.text(),
    				name:username_staff,
    				job:position_staff,
    				phone:phone_staff,
    				idCardNo:ID_staff,
    				education:education_staff,
    				entryTime:entry_date,
    				hireTime:contract_date,
    				gangwei:position_salary_staff,
    				baozhang:guarantee_salary_staff,
    				roleId:roleOptions.val(),
    				insurance:localStorage.getItem("isInsurance")==1,
    				avatar:head_img,
    				annualSalary:annualSalary,
    				currentResidence:address,
					wxjishu:social_insurance_base,
					professional:professional,
					politicalStatus:political
    			}
    			
    			var URL = site_url+"/users";
    			var userToken=localStorage.getItem("userToken");
    			$.ajax({
    				type:"POST",
    				url:URL,
    				headers:{'token':userToken},
    				contentType: 'application/json; charset=utf-8',
    				data:JSON.stringify(data),
    				success: function (json) {
    			      // layer.alert("保存成功！", {icon: 6});
					  location.reload();
    			    }
    			});
	        }
		}else{
			var data = {
				deptId:parseInt(deptOptions.val()),
				deptName:deptOptions.text(),
				name:username_staff,
				job:position_staff,
				phone:phone_staff,
				idCardNo:ID_staff,
				education:education_staff,
				entryTime:entry_date,
				hireTime:contract_date,
				gangwei:position_salary_staff,
				baozhang:guarantee_salary_staff,
				roleId:roleOptions.val(),
				insurance:localStorage.getItem("isInsurance")==1,
				avatar:head_img,
				annualSalary:annualSalary,
				currentResidence:address,
				wxjishu:social_insurance_base,
				professional:professional,
				politicalStatus:political
			}
			
			var URL = site_url+"/users";
			var userToken=localStorage.getItem("userToken");
			$.ajax({
				type:"POST",
				url:URL,
				headers:{'token':userToken},
				contentType: 'application/json; charset=utf-8',
				data:JSON.stringify(data),
				success: function (json) {
			      // layer.alert("保存成功！", {icon: 6});
				  location.reload();
			    }
			});
		}
		
	});	
}
/* 给员工页面赋值 */
function getDataStaff(records){
	$('#data').html("");
	var html="";
	html+='<table id="tbData">';
	html+='<tr class="table-top">';
	
	html+='<td width="5%"><input id="allCheck" type="checkbox" value="0" onchange="selectAll()"></td><td width="7%">头像</td>';
	html+='<td width="10%">姓名</td><td width="10%">部门</td><td width="8%">职位</td><td width="6%">学历</td><td width="6%">工龄</td>';
	html+='<td width="15%">入职时间</td><td width="15%">交纳五险</br>时间</td><td width="6%">类型</td><td width="12%">操作</td></tr>';
	for (var i=0;i<records.length;i++) {
		if(i%2==0){
			html+='<tr class="item-white">';
		}else{
			html+='<tr class="item-blue">';
		}

		html+='<td><input type="checkbox" name="dataId" value="'+records[i].id+'"></td>';
		html+='<td><img class="depart_staff-head" src="img/touxiang.png"></td>';
		html+='<td>'+(records[i].name==undefined?"":records[i].name)+'</td>';
		html+='<td>'+(records[i].deptName==undefined?"":records[i].deptName)+'</td>';
		html+='<td>'+(records[i].job==undefined?"":records[i].job)+'</td>';
		html+='<td>'+(records[i].education==undefined?"":records[i].education)+'</td>';
		html+='<td>'+(records[i].worksYear==undefined?"":records[i].worksYear)+'</td>';
		// html+='<td>'+(records[i].idCardNo==undefined?"":records[i].idCardNo)+'</td>';
		html+='<td>'+(records[i].entryTime==undefined?"":records[i].entryTime)+'</td>';
		html+='<td>'+(records[i].hireTime==undefined?"":records[i].hireTime)+'</td>';
		html+='<td>'+(records[i].valid?records[i].signing?"入职":"未入职":"离职")+'</td>';
		html+='<td>';
		html+='<img src="img/edit_icon.png" onclick="popupShow(6,0,\''+records[i].id+'\');"/>';
		html+='<img class="btnDelete" style="margin-left: 10px;" src="img/delete_icon.png" onclick="dataDelete(3,0,\''+records[i].id+'\');"/>';
		html+='</td>';
		html+='</tr>';
	}
	if(records.length<=0){
		html+='<tr class="item-white">';
		html+='<td colspan="11"><div>暂无数据</div></td>';
		html+='</tr>';
	}
	html+='</table>';
	$('#data').html(html);
}
/* 头像 type:1：添加  2：编辑*/
function headChange(type,file){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		if (!file.files || !file.files[0]){
		    return;
		}else{
		    var name=file.files[0].name;
		    var extName = name.substring(name.lastIndexOf(".")+1).toLowerCase();
		    if(extName=="gif" || extName=="jpg" || extName=="png" || extName=="jpeg"){
		    }else{
				layer.alert("图片格式不正确！", {icon: 5});
		        return;
		    }
		}
		
		
		var windowURL = window.URL || window.webkitURL;
		var fileObj = file;
		var dataURL;
		dataURL = windowURL.createObjectURL(fileObj.files[0]);
		// alert(dataURL);
		if(type==1){
			$("#head_img").attr('src', dataURL);
		}else if(type==2){
			$("#head_img_edit").attr('src', dataURL);
		}
	});
}
/* 选择头像 */
function imgClick(type){
	if(type==1){
		$("#headFileAdd").click();
	}else{
		$("#headFileEdit").click();
	}
	
}

function usersPage(insurance){
	var pageNo=$('#pageNo').val();
	
	var valid = $("#is_valid option:selected").val();
	
	var signing=$("#is_signing option:selected").val();
    
    var start=$('#search_date_start').val();
    
    var end=$('#search_date_end').val();
    
    var keyword=$('#search_keyword').val();
    var ifSigning="";
	if(signing==1){
		ifSigning=true;
	}else{
		ifSigning=false;
	}
	if(insurance){
		localStorage.setItem("isInsurance",1);
	}else{
		localStorage.setItem("isInsurance",0);
	}
	requestStatus=false;
	$('#page').html("");
	$('#pageNo').val("1");
	getUserById(1);
	//alert(insurance);
	/* var URL = site_url+"/users/pages?size=10&current="+pageNo+"&signing="+signing+"&start="+start+"&end="+end+"&name="+keyword+"&insurance="+insurance;
	var URL = site_url+"/users/pages?size=10&current="+pageNo+"&signing="+signing+"&valid="+valid+"&start="+start+"&end="+end+"&name="+keyword+"&insurance="+insurance;
	
	
	var userToken=localStorage.getItem("userToken");
	$.ajax({
		type:'GET',
		url:URL,
		headers:{'token':userToken},
		dataType:"json",
		success: function (json) {
			
			var total_page=json.data.total/9;
			$('#total_page').val(json.data.pages);
			$('#total_rows').val(json.data.total);
			
	      getDataStaff(json.data.records);
	      var pageNo=json.data.current;
			var total_page=json.data.pages;
			//分页
			$("#page").paging({
			    pageNo: parseInt(pageNo),
			    totalPage: parseInt(total_page),
			    // totalSize: total_rows,
			    callback: function(num) {
					usersPage(num);
			    }
			})
	    }
	}); */
}



function getByUserId(id){
	
	var URL = site_url+"/users?id="+id;
	var userToken=localStorage.getItem("userToken");
	var userInfo;
	
	$.ajax({
		type:'GET',
		url:URL,
		headers:{'token':userToken},
		dataType:"json",
		async:false,
		success: function (json) {
	      userInfo = json.data;
	    }
	});

	return userInfo;
}

function getByParentId(id){
	
	var URL = site_url+"/depts/parent?id="+id;
	var userToken=localStorage.getItem("userToken");
	var depts;
	$.ajax({
		type:'GET',
		url:URL,
		headers:{'token':userToken},
		dataType:"json",
		async:false,
		success: function (json) {
	      depts = json.data;
		  // alert(depts);
	    }
	});

	return depts;
}
/* 人员编辑 */
function staffEditSave(){
	
		layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
	    var id_staff = $("#id_staff_edit").val();
		var department_staff = $("#department_staff_edit").val(); //部门
		var username_staff = $("#username_staff_edit").val();     //姓名
		var position_staff = $("#position_staff_edit").val();     //职位
		var phone_staff = $("#phone_staff_edit").val();           //电话
		var ID_staff = $("#ID_staff_edit").val();                 //身份证
		var education_staff = $("#education_staff_edit").val();   //学历
		var entry_date = $("#entry_date_edit").val();             //入职时间
		var contract_date = $("#contract_date_edit").val();       //合同时间
		var position_salary_staff = $("#position_salary_staff_edit").val();   //岗位工资
		var guarantee_salary_staff = $("#guarantee_salary_staff_edit").val();  //保障工资
		var role_id = $("#role_staff_edit").val();
		var social_insurance_base = $("#social_insurance_base_edit").val();//缴费基数
		var annualSalary = $("#annual_salary_edit").prop("checked");
		var address = $("#address_edit").val();    //家庭住址
		var professional =$("#major_edit").val();  //专业
		var political=$("#political_edit").val();  //政治面貌
//		 var head_img = $("#head_img").val();//头像
		var data = {
			id:id_staff,
			deptId:department_staff,
			deptName:$("#department_staff_edit option:selected").text(),
			name:username_staff,
			job:position_staff,
			phone:phone_staff,
			idCardNo:ID_staff,
			education:education_staff,
			entryTime:entry_date,
			hireTime:contract_date,
			gangwei:position_salary_staff,
			baozhang:guarantee_salary_staff,
			roleId:role_id,
			insurance:localStorage.getItem("isInsurance")==1,
			annualSalary:annualSalary,
			currentResidence:address,
			wxjishu:social_insurance_base,
			professional:professional,
			politicalStatus:political
		}
		
		var URL = site_url+"/users";
		var userToken=localStorage.getItem("userToken");
		$.ajax({
			type:"PUT",
			url:URL,
			headers:{'token':userToken},
        	contentType: 'application/json; charset=utf-8',
			data:JSON.stringify(data),
			success: function (json) {
		      	// layer.alert("修改成功！", {icon: 6});
				location.reload();
		    }
		});
	});	
	
}

function deleteUserById(id){
	layui.use(['element', 'layer'], function() {
	var URL = site_url+"/users?id="+id;
	var userToken=localStorage.getItem("userToken");
		$.ajax({
			type:"DELETE",
			url:URL,
			headers:{'token':userToken},
			dataType:"json",
			async:false,
			success:function(data){
				window.location.reload();
				layer.alert("删除成功！", {icon: 6})
			}
		});
	})
}

function tabClick(isInsurance){
	if (isInsurance==1) {
		window.location.href="department_pay.html";
	}else{
		window.location.href="department_unpay.html";
	}
	// alert("========="+isInsurance);
	localStorage.setItem("isInsurance",isInsurance)
}


function getDeptById(id,type){
	type==1?$("#partent_name_add").html(""):$("#partent_subject_add").html("");
	var URL = site_url+"/depts?id="+id;
	var userToken=localStorage.getItem("userToken");
	$.ajax({
		type:"get",
		url:URL,
		headers:{'token':userToken},
		success:function(data){
			var querynames = $('<option value="'+data.data.id+'">'+data.data.name+'</option>');
				type==1?$("#partent_name_add").append(querynames):$("#partent_subject_add").append(querynames);
			
		}
	});
}

//查询部门
function getProject(){
	$("#department_staff_edit").html("");
	var URL = site_url+"/depts/all";
	var userToken=localStorage.getItem("userToken");
	$.ajax({
		type:"get",
		url:URL,
		headers:{'token':userToken},
		success:function(data){
			
			for(var i = 0; i<data.length;i++){
				var querynames = $('<option value="'+data[i].id+'">'+data[i].name+'</option>');
				$("#department_staff_edit").append(querynames);
				$("#search_department").append(querynames);
			}
		}
	});
}


function removeById(URL){
	layui.use(['element', 'layer'], function() {
		var userToken=localStorage.getItem("userToken");
		$.ajax({
			type:"DELETE",
			url:URL,
			headers:{'token':userToken},
			success:function(data){
				location.reload();
				// layer.alert("删除成功！", {icon: 6});
			}
		});
	})
}
/* 添加保障工资的类别 */
function addSalaryType(){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		var typeName=$("#typename").val();
		
		var baozhang = getBaoZhang();
		
		var userToken=localStorage.getItem("userToken");
		
		$.ajax({
			type:"POST",
			url:site_url+"/dicts/",
			headers:{'token':userToken},
			contentType: 'application/json; charset=utf-8',
			data:JSON.stringify({
				type:baozhang[baozhang.length-1].type,
				description:baozhang[baozhang.length-1].description,
				label:typeName,
				value:parseInt(baozhang[baozhang.length-1].value)+1,
				sort:parseInt(baozhang[baozhang.length-1].sort)+1,
				valid:true
			}),
			success:function(data){
				layer.alert("保存成功！", {icon: 6});
				$("#guarantee_salary_staff").html("");
				$("#guarantee_salary_staff_edit").html("");
				var baozhang = getBaoZhang();
				for(var i=0;i<baozhang.length;i++){
					$("#guarantee_salary_staff").append( $('<option value="'+baozhang[i].value+'">'+baozhang[i].label+'</option>'));
					$("#guarantee_salary_staff_edit").append( $('<option value="'+baozhang[i].value+'">'+baozhang[i].label+'</option>'));
					
				}
				
			}
		});
		$("#typename").val("");
		$("#typeDiv").hide();
	});
}
/* 添加职位的类别 */
function addPositionType(){
	layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		var typeName=$("#positionName").val();
		var addPositionId=$("#addPositionId").val();
		
		var job = getPositionType();
		
		var userToken=localStorage.getItem("userToken");
		
		$.ajax({
			type:"POST",
			url:site_url+"/dicts/",
			headers:{'token':userToken},
			contentType: 'application/json; charset=utf-8',
			data:JSON.stringify({
				type:job[job.length-1].type,
				description:job[job.length-1].description,
				label:typeName,
				value:parseInt(job[job.length-1].value)+1,
				sort:parseInt(job[job.length-1].sort)+1,
				valid:true
			}),
			success:function(data){
				layer.alert("保存成功！", {icon: 6});
				var job = getPositionType();
				$("#position_staff").html("");
				$("#position_staff_edit").html("");
				for(var i=0;i<job.length;i++){
					$("#position_staff").append( $('<option value="'+job[i].value+'">'+job[i].label+'</option>'));
					$("#position_staff_edit").append( $('<option value="'+job[i].value+'">'+job[i].label+'</option>'));
				}
			}
		});
		
		$("#addPositionDiv").hide();
	});
}

/*查询职位*/
function getPositionType () {
	$("#position_staff").html("");
	$("#position_staff_edit").html("");
	var result = [];
	var userToken = localStorage.getItem("userToken");
	$.ajax({
		url:site_url+"/dicts/job",
		dataType:'json',
		async:false,
		headers:{'token':userToken},
		success:function(data){
			result = data.data;
		}
	})
	return result;
}

/*查询保障金*/
function getBaoZhang () {
	var result = [];
	var userToken = localStorage.getItem("userToken");
	$("#guarantee_salary_staff").html("");
	$("#guarantee_salary_staff_edit").html("");
	$.ajax({
		url:site_url+"/dicts/baozhang",
		dataType:'json',
		async:false,
		headers:{'token':userToken},
		success:function(data){
			result = data.data;
		}
	})
	return result;
}
/*查询角色*/
function getRole () {
	var result = [];
	var userToken = localStorage.getItem("userToken");
	$.ajax({
		url:site_url+"/roles/all",
		dataType:'json',
		async:false,
		headers:{'token':userToken},
		success:function(data){
			result = data.data;
		}
	})
	return result;
}
/*查询部门*/
function getDepart () {
	var result = [];
	var userToken = localStorage.getItem("userToken");
	$.ajax({
		url:site_url+"/depts/all",
		dataType:'json',
		async:false,
		headers:{'token':userToken},
		success:function(data){
			result = data;
		}
	})
	return result;
}
/*查询政治面貌*/
function getPolitical () {
	var result = [];
	var userToken = localStorage.getItem("userToken");
	$.ajax({
		url:site_url+"/dicts/political",
		dataType:'json',
		async:false,
		headers:{'token':userToken},
		success:function(data){
			result = data.data;
		}
	})
	return result;
}

